// businessService.ts
import {computed, ref} from 'vue';
import { message } from 'ant-design-vue';
import api from "@/utils/api";
import {fetchFailModes} from "./failModeService.ts";

// 定义接口
export interface Business {
    id: number;
    name: string;
    createDate: string;
    updateDate: string;
    createUser: string;
    updateUser: string;
}

// 定义响应式变量
export const businessList = ref<Business[]>([]);
export const fetching = ref(false);
export const selectedBusiness = ref<any>(undefined);
export const selectedBusinessObj = ref<any>(null);

export const newBusinessName = ref();


export const isBusinessNew = computed(() => {
    return (newBusinessName && newBusinessName.value!==undefined)
})
// 业务搜索方法
export const onBusinessSearch = async (keyword: string, roleName?: string) => {
    await fetchBusinesses(keyword, roleName);
};

// 获取业务列表
export const fetchBusinesses = async (keyword: string = '', roleName?: string) => {
    try {
        fetching.value = true;

        const response = await api.get('/business/dtoRoleCase', {
            params: {
                roleName: roleName,
                name: keyword
            }
        });
        if(keyword.length>0){
            newBusinessName.value = keyword;
        }
        businessList.value = response.data;
    } catch (error) {
        message.error('获取业务列表失败');
        console.error('获取业务列表失败:', error);
    } finally {
        fetching.value = false;
    }
};

// 业务焦点事件
export const onBusinessFocus = (roleName?: string) => {
    if (!roleName) {
        message.warning('请先选择角色');
        return;
    }

    // 如果业务列表为空，调用空搜索
    if (businessList.value.length === 0) {
        fetchBusinesses('', roleName);
    }
};

// 业务失焦事件
export const onBusinessBlur = () => {
    // 检查当前输入的业务是否是新业务
    if (isBusinessNew.value) {
        selectedBusiness.value = newBusinessName.value;
    }
};

// 业务选择变化
export const onBusinessChange = (value: any) => {
    selectedBusinessObj.value = businessList.value.find(business =>
        business.id === value
    );

    if (selectedBusinessObj.value) {
        newBusinessName.value = undefined;
        if(selectedBusinessObj.value.roleCaseId){
            fetchFailModes(selectedBusinessObj.value.roleCaseId);
        }
    }

    // 返回变化信息，用于清空相关数据
    return {
        businessCleared: true
    };
};

// 创建新业务
export const createNewBusiness = async (roleId: number, businessName: string) => {
    try {
        fetching.value = true;

        await api.post('/business/roleBusiness', {
            roleId: roleId,
            name: businessName,
        });

        // 重新获取业务列表以更新数据
        await fetchBusinesses(businessName);

        // 更新选中的业务对象
        selectedBusinessObj.value = businessList.value.find(business =>
            business.name === businessName
        );
        newBusinessName.value=undefined;

        message.success(`新业务【${businessName}】创建成功`);
        return true;
    } catch (error) {
        message.error('创建业务失败');
        console.error('创建业务失败:', error);
        return false;
    } finally {
        fetching.value = false;
    }
};

// 重置业务数据
export const resetBusinessData = () => {
    selectedBusiness.value = '';
    selectedBusinessObj.value = null;
    businessList.value = [];
    newBusinessName.value = undefined;
};

// 导出所有方法
export default {
    businessList,
    fetching,
    selectedBusiness,
    selectedBusinessObj,
    newBusinessName,
    isBusinessNew,
    onBusinessSearch,
    fetchBusinesses,
    onBusinessFocus,
    onBusinessBlur,
    onBusinessChange,
    createNewBusiness,
    resetBusinessData
};